package com.lorizz.docrepo.repository.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;

import com.lorizz.docrepo.DocrepoException;

public class JcrUtils {

    @SuppressWarnings("unchecked")
    public static <T> T nullSafeGetPropertyValue(Node node, String name,
            int type) {
        try {
            Property p = node.getProperty(name);
            switch (type) {
            case PropertyType.BINARY:
                return (T) p.getBinary();
            case PropertyType.BOOLEAN:
                return (T) new Boolean(p.getBoolean());
            case PropertyType.DATE:
                return (T) p.getDate();
            case PropertyType.DECIMAL:
                return (T) p.getDecimal();
            case PropertyType.DOUBLE:
                return (T) new Double(p.getDouble());
            case PropertyType.LONG:
                return (T) new Long(p.getLong());
            default:
                return (T) p.getString();
            }
        } catch (PathNotFoundException e) {
            return null;
        } catch (RepositoryException e) {
            throw new DocrepoException(e);
        }
    }

    public static byte[] readBinary(Binary bin) {
        if (bin == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024*1024];
            InputStream is = bin.getStream();
            int numRead = 0;
            while ((numRead = is.read(buffer)) > 0) {
                os.write(buffer, 0, numRead);
            }
            return os.toByteArray();
        } catch (RepositoryException e) {
            throw new DocrepoException(e);
        } catch (IOException e) {
            throw new DocrepoException(e);
        }
    }

}
